<?php

namespace common\entities\common;


use common\entities\ConfigEntity;
use common\repositories\myhtsq\ContractManageRepository;
use common\support\StringHelper;
use Yii;

/**
 * This is the model class for table "myscrm_contract".
 *
 * @property string $ContractId
 * @property string $ContractNum
 * @property string $PartyA
 * @property integer $ContractType
 * @property string $BeginOn
 * @property string $EndOn
 * @property string $OrganizationId
 * @property integer $Status
 * @property string $AreaId
 * @property string $EstablishTime
 * @property string $ParentContractId
 * @property string $PerformanceAccountingTime
 * @property string $order_code
 * @property string $order_guid
 */
class MyscrmContractEntity extends ConfigEntity
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'myscrm_contract';
    }

    public static function globalTableName()
    {
        preg_match("/dbname=([^;]+)/i", self::getDb()->dsn, $matches);
        return $matches[1].'.myscrm_contract';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['ContractId', 'ContractNum', 'OrganizationId'], 'required'],
            [['ContractType', 'Status'], 'integer'],
            [['BeginOn', 'EndOn', 'EstablishTime','PerformanceAccountingTime','order_code','order_guid'], 'safe'],
            [['ContractId', 'OrganizationId', 'AreaId', 'ParentContractId'], 'string', 'max' => 36],
            [['ContractNum'], 'string', 'max' => 64],
            [['PartyA'], 'string', 'max' => 512]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ContractId' => 'Contract ID',
            'ContractNum' => 'Contract Num',
            'PartyA' => 'Party A',
            'ContractType' => 'Contract Type',
            'BeginOn' => 'Begin On',
            'EndOn' => 'End On',
            'OrganizationId' => 'Organization ID',
            'Status' => 'Status',
            'AreaId' => 'AreaId',
            'EstablishTime' => 'EstablishTime',
            'ParentContractId' => 'ParentContractId',
            'PerformanceAccountingTime' => 'PerformanceAccountingTime',
            'order_code' => '出库单号',
            'order_guid' => '出库单GUID',
        ];
    }
    
    
    /**
     * 根据合同编号，获取模型数据
     * @param string $contractNum 合同编号
     * @param string $orgId 租户Id
     * @return MyscrmContractEntity array 实体数据
     */
    public static function getContractByContractNum($contractNum, $orgId=null) {

        return self::find()->where(['ContractNum'=>$contractNum])
            ->andFilterWhere(['OrganizationId' => $orgId])
            ->orderBy('EstablishTime ASC')
            ->one();
    }

    /**
     * 根据合同编号,获取所有模型数据(一个合同可以授权多次)
     * @param $contractNum
     * @param null $orgId
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getAllContractByContractNum($contractNum, $orgId = null)
    {

        return self::find()->where(['ContractNum' => $contractNum])
            ->andFilterWhere(['OrganizationId' => $orgId])
            ->all();
    }

    /**
     * 获取合同信息
     * @param array
     * @since 2017-7-23
     * @author zhoud01
     * @return boolean
     */
    public static function getContractByContractId($contractId)
    {
        return self::find()->where(['ContractId'=>$contractId])
            ->asArray()
            ->one();
    }


    /**
     * 判断合同是否过期
     * @param $contract
     * @return bool
     */
    public static function isContractOverdue($contract){
        if(!empty($contract) && isset($contract['EndOn'])){
            if(strtotime($contract['EndOn']) >= time()){
                return false;
            }
        }

        return true;
    }

    /**
     * 新增合同记录
     * @param array
     * @since 2017-7-23
     * @author zhoud01
     * @return boolean
     */
    public static function addContract($arr) {

        $status = false;
        if(!empty($arr)){
            if($arr['handleType']==='add'){
                $isExistContractId = self::findOne($arr['contractId']);
                if(empty($isExistContractId)){
                    $addAddContract = new MyscrmContractEntity();
                    $addAddContract->ContractId = $arr['contractId'];
                    $addAddContract->ContractNum = $arr['contract_num'];
                    $addAddContract->ContractType = $arr['contract_type'];
                    $addAddContract->order_code = isset($arr['order_code']) && $arr['order_code'] ? $arr['order_code']:'';
                    $addAddContract->order_guid = isset($arr['order_guid']) && $arr['order_guid'] ? $arr['order_guid']:'';
                    $addAddContract->BeginOn = $arr['begin_on'];
                    $addAddContract->EndOn = $arr['end_on'];
                    $addAddContract->OrganizationId = (isset($arr['organization_id'])&&$arr['organization_id'])?$arr['organization_id']:StringHelper::uuid();//这个要填 目前随机生成有可能取值不正确,问下永波
                    $addAddContract->EstablishTime = date("Y-m-d" ,time());//业绩核算时间 新增时默认为当天
                    $addAddContract->PerformanceAccountingTime = $arr['establish_time'];//开通时间
                    $addAddContract->CreatedOn = date("Y-m-d H:i:s" ,time()) ;
                    $res = $addAddContract->save();
                    //sonar 坏味道修复
                    return $res?$addAddContract->attributes['ContractId']:false;
                }else{
                    $addAddContract = self::findOne($arr['contractId']);
//                    $currentContract = ContractManageRepository::getContractMangeIdsByCode($addAddContract->ContractNum);
//                    $isSpecialApproval = $currentContract?false:true;
                    if(!empty($arr['contract_type'])){
                        $addAddContract->ContractType = (int)$arr['contract_type'];
                    }
                    if(!empty($arr['begin_on'])){
                        $addAddContract->BeginOn = $arr['begin_on'];
                    }
                    if(!empty($arr['contract_num'])){
                        $addAddContract->ContractNum = $arr['contract_num'];
                    }
                    if(!empty($arr['end_on'])){
                        $addAddContract->EndOn = $arr['end_on'];
                    }
                    // establish_time 代表的是业绩核算时间,特批合同的业绩核算时间=授权的当天
                    if(isset($arr['isSpecialAuthor']) && $arr['isSpecialAuthor']){
                        $addAddContract->EstablishTime = date("Y-m-d" ,time());//业绩核算时间 新增时默认为当天
                    }else{
                        $addAddContract->EstablishTime = $arr['establish_time'];
                    }
                    if(!empty($arr['order_code'])){
                        $addAddContract->order_code = $arr['order_code'];
                    }
                    if(!empty($arr['order_guid'])){
                        $addAddContract->order_guid = $arr['order_guid'];
                    }

                    $addAddContract->ModifiedOn = date("Y-m-d H:i:s" ,time());
                    $res = $addAddContract->save();

                    //sonar 坏味道修复
                    return $res?$addAddContract->attributes['ContractId']:false;
                }

            } else if($arr['handleType']==='edit'){

                $addAddContract = self::findOne($arr['contractId']);
                //特批授权，在合同回来之前合同编号是不对的，所以根据合同编号查不到合同的便是特批
                $currentContract = ContractManageRepository::getContractMangeIdsByCode($addAddContract->ContractNum);
                $isSpecialApproval = $currentContract?false:true;

                if(!empty($arr['contract_type'])){
                    $addAddContract->ContractType = (int)$arr['contract_type'];
                }
                if(!empty($arr['begin_on'])){
                    $addAddContract->BeginOn = $arr['begin_on'];
                }
                if(!empty($arr['end_on'])){
                    $addAddContract->EndOn = $arr['end_on'];
                }
                if(!empty($arr['contract_num'])){
                    $addAddContract->ContractNum = $arr['contract_num'];
                }
                // establish_time 代表的是业绩核算时间,特批合同的业绩核算时间=授权的当天
                if(isset($arr['isSpecialAuthor']) && $arr['isSpecialAuthor']){
                    $addAddContract->EstablishTime = date("Y-m-d" ,time());//业绩核算时间 新增时默认为当天
                }else{
                    $addAddContract->EstablishTime = $arr['establish_time'];
                }
                if(!empty($arr['order_code'])){
                    $addAddContract->order_code = $arr['order_code'];
                }
                if(!empty($arr['order_guid'])){
                    $addAddContract->order_guid = $arr['order_guid'];
                }

                $addAddContract->ModifiedOn = date("Y-m-d H:i:s" ,time());
                $res = $addAddContract->save();

                //sonar 坏味道修复
                return $res?$addAddContract->attributes['ContractId']:false;
            } else {
                if(!empty($arr['id'])){// 如果有id表示为修改
                    $addAddContract = self::findOne($arr['ContractId']);

                    if(!empty($arr['contract_type'])){
                        $addAddContract->ContractType = (int)$arr['contract_type'];
                    }
                    if(!empty($arr['begin_on'])){
                        $addAddContract->BeginOn = $arr['begin_on'];
                    }
                    if(!empty($arr['end_on'])){
                        $addAddContract->EndOn = $arr['end_on'];
                    }

                    if(!empty($arr['establish_time'])){
                        $addAddContract->EstablishTime = $arr['establish_time'];//业绩核算时间
                    }
                    if(!empty($arr['performance_accounting_time'])){
                        $addAddContract->PerformanceAccountingTime = $arr['performance_accounting_time'];//开通时间
                    } else {
                        $addAddContract->PerformanceAccountingTime = date("Y-m-d" ,time());//开通时间
                    }
                    if(!empty($arr['order_code'])){
                        $addAddContract->order_code = trim($arr['order_code']);
                    }
                    $addAddContract->ModifiedOn = date("Y-m-d H:i:s" ,time());
                    $res = $addAddContract->save();
                    //sonar 坏味道修复
                    return $res?$addAddContract->attributes['ContractId']:false;
                }else{
                    $addAddContract = new MyscrmContractEntity();
                    $addAddContract->ContractId = StringHelper::uuid();
                    $addAddContract->ContractNum = $arr['contract_num'];
                    $addAddContract->ContractType = $arr['contract_type'];
                    $addAddContract->order_code = $arr['order_code'];
                    $addAddContract->BeginOn = $arr['begin_on'];
                    $addAddContract->EndOn = $arr['end_on'];
                    $addAddContract->order_code = trim($arr['order_code']);
                    $addAddContract->OrganizationId = StringHelper::uuid();//这个要填 目前随机生成有可能取值不正确,问下永波
                    $addAddContract->EstablishTime = $arr['establish_time']?$arr['establish_time']:date("Y-m-d" ,time());;//业绩核算时间 新增时默认为当天
                    $addAddContract->PerformanceAccountingTime = $arr['performance_accounting_time']?$arr['performance_accounting_time']:date("Y-m-d" ,time());//开通时间
                    $addAddContract->CreatedOn = date("Y-m-d H:i:s" ,time()) ;
                    $res = $addAddContract->save();
                    //sonar 坏味道修复
                    return $res?$addAddContract->attributes['ContractId']:false;
                }
            }
        }
        return $status;
    }
}
